home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: uu4news.netcom.com!zodiac!szh
- From: szh@zcon.com (Syed Zaeem Hosain)
- Subject: Re: help:what is wrong with this code?
- Message-ID: <1996Apr15.005244.14555@zcon.com>
- Sender: szh@zcon.com (Syed Zaeem Hosain)
- Nntp-Posting-Host: zodiac
- Reply-To: szh@zcon.com
- Organization: Z Consulting Group
- References: <4krmdu$t3h@brahms.udel.edu>
- Date: Mon, 15 Apr 1996 00:52:44 GMT
-
- In article <4krmdu$t3h@brahms.udel.edu>, yuehong@brahms.udel.edu (Yue-hong Zheng) writes:
- >#include <stdio.h>
- >
- >void quicksort(int[],int,int );
- >
- >void swap(int*,int*);
- >
- >main () {
- >int k;
- >int a[]={1,3,4,2,43,23,5,6,87,92,21};
- >quicksort(a,0,10);
- >for (k=0;k<=10;k++) {
- >printf("%d\n",a[k]);
- >}
- >return 0;
- >}
- >
- >
- >void swap( int* s,int* t) {
- >int tmp;
- >tmp=*s;
- >*s=*t;
- >*t=tmp;
- >}
- >
- >void quicksort(int array[],int left,int right) {
- >int i,j,median;
- >if (right<=left) return ;
- >median=(right+left)/2;
- >swap(&array[median],&array[right]);
- >i=left;
- >j=right-1;
- >while((j-i)>=-1){
- >while((array[i]<array[right])&&(i<=(right-1)))
- >i++;
- >while((array[j]>array[right])&&(j>=0))
- >j--;
-
- If you look at the value of 'j' right here in the code, you will see
- that it becomes equal to -1 for some steps. Hence, the swap in the
- next line is incorrect, as it accesses memory outside the array. Try
- fixing that and proceeding with the next step in figuring out the
- error.
-
- One other minor nitpick: your indentation (or lack thereof really)
- makes it very tough to see what is going on. I had to re-indent the
- code to follow it more cleanly.
-
- >swap(&array[i],&array[j]);
- >}
- >swap(&array[i],&array[right]);
- >quicksort(array,left,(i-1));
- >quicksort(array,(i+1),right);
- >}
-
-
- --
- -------------------------------------------------------------------------
- | Syed Zaeem Hosain P. O. Box 610097 (408) 441-7021 |
- | Z Consulting Group San Jose, CA 95161 szh@zcon.com |
- -------------------------------------------------------------------------
-